//
//  CZNetWorkingTool.swift
//  WHWeiBo
//
//  Created by Li Changjian on 16/7/10.
//  Copyright © 2016年 Li Changjian. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType: Int {
    case GET
    case POST
}

class CZNetWorkingTool:  AFHTTPSessionManager{
    
    static var sharedNetWorkTool :CZNetWorkingTool = {
        let tool = CZNetWorkingTool()
        tool.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tool
    
    }()
    
    
    func request(requestType: RequestType, url: String, param: AnyObject?, callBack:(reponse: AnyObject?, error: NSError?) -> ()) {
        
        if requestType == .GET {
            //GET请求
            GET(url, parameters: param, progress: nil, success: { (_, response) -> Void in
                    callBack(reponse: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(reponse: nil, error: error)
            })
            
        }else {
            //POST请求
            POST(url, parameters: param, progress: nil, success: { (_, response) -> Void in
                    callBack(reponse: response, error: nil)
                }, failure: { (_, error) -> Void in
                    callBack(reponse: nil, error: error)
            })
        }
        
        
    }
    

}


 // MARK: - 根据code获取accesstoken进一步获取用户信息
extension CZNetWorkingTool {
   
    //根据code获取accessToken
    func requestAccessToken(code: String, callBack: (response: AnyObject?, error: NSError?) -> ()){
        let url = "https://api.weibo.com/oauth2/access_token"
        let param = [
                "client_id" : client_id,
            "client_secret" : client_secret,
               "grant_type" : "authorization_code",
                     "code" : code,
             "redirect_uri" : redirect_uri
        ]
        request(.POST, url: url, param: param, callBack: callBack)
    }
    
    
    //根据accessToken和uid获取用户信息
    func requestUserAccount(userAccount: CZUserAccount, callBack: (response: AnyObject?, error: NSError?) -> ()){
        let url = "https://api.weibo.com/2/users/show.json"
        let param = [
            "access_token": userAccount.access_token!,
            "uid": "\(userAccount.uid)"
        ]
        
//        print(url + "?access_token=" + userAccount.access_token! + "&uid=\(userAccount.uid)")
        request(.GET, url: url, param: param, callBack: callBack)
    }
}
